<template>
  <!-- <el-date-picker></el-date-picker> -->
  <div class="date-content">
    <el-tabs
      v-model="activeTab"
      style="margin-bottom: 16px"
    >
      <el-tab-pane
        label="静态时间"
        name="static"
      >
        <div class="static-buttons">
          <el-button
            v-for="(item, index) in staticRanges"
            :key="index"
            size="small"
            type="default"
            @click="selectStaticRange(item.range)"
            class="date-btn"
          >
            {{ item.label }}
          </el-button>
        </div>
      </el-tab-pane>

      <el-tab-pane
        label="动态时间"
        name="dynamic"
      >
        <el-radio-group
          v-model="dynamicType"
          size="small"
          style="margin-bottom: 12px"
        >
          <el-radio-button label="specific">具体时间</el-radio-button>
          <el-radio-button
            label="pastNDays"
            class="pastNDays"
            >过去N天</el-radio-button
          >
        </el-radio-group>

        <!-- <el-button size="small" type="default" @click="dynamicType = 'specific'" class="dynamic-btn">具体时间</el-button>
        <el-button size="small" type="primary" @click="dynamicType = 'pastNDays'"
          class="dynamic-btn past-n-days">过去N天</el-button> -->

        <!-- <div v-if="dynamicType === 'specific'">
          <n-config-provider :locale="zhCN" :date-locale="dateZhCN">
            <n-date-picker v-model:value="dynamicRange" type="daterange" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
              @update:value="onDynamicRangeChange" :clearable="true" style="width: 320px;" />
          </n-config-provider>
        </div> -->

        <!-- 具体时间 -->

        <!-- 过去N天 -->
        <div v-if="dynamicType === 'pastNDays'">
          <el-form
            :model="pastNDays"
            :rules="rules"
            ref="formRef"
          >
            <el-form-item prop="nDays">
              <el-input
                v-model="pastNDays.nDays"
                label="过去N天"
                size="small"
                style="width: 120px; margin-right: 12px"
              />
              <el-button
                size="small"
                type="primary"
                @click="confirmPastNDays"
                >确认</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-tab-pane>
      <div style="margin-top: 24px">
        <n-config-provider
          :locale="zhCN"
          :date-locale="dateZhCN"
        >
          <n-date-picker
            v-model:value="selectedRange"
            panel
            type="daterange"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            @update:value="onSelectedRangeChange"
            :clearable="true"
            style="width: 320px"
            placeholder="选择时间范围"
          />
        </n-config-provider>
      </div>

      <div>
        <el-button @click="cancelDateRange">取消</el-button>
        <el-button @click="resetDateRange">重置</el-button>
        <el-button
          type="primary"
          @click="onHandleConfirm"
        >
          确定
        </el-button>
      </div>
    </el-tabs>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, inject } from "vue";
import dayjs from "dayjs";
import {
  ElTabs,
  ElTabPane,
  ElButton,
  ElRadioGroup,
  ElRadio,
  ElInputNumber,
  ElMessage,
} from "element-plus";
import { NConfigProvider, NDatePicker, NButton } from "naive-ui";
import { zhCN, dateZhCN } from "naive-ui";
const props = defineProps<{
  datePicker: [string, string] | null;
}>();

//接收父组件传参
const getDateRange = ref(props.datePicker || null);
console.log("getDateRange", getDateRange);
// 选中的时间范围，绑定到底部时间范围选择器
const selectedRange = ref<[number, number] | null>(null);

if (getDateRange.value && getDateRange.value.length) {
  const start = dayjs(getDateRange.value[0]).valueOf();
  const end = dayjs(getDateRange.value[1]).valueOf();
  selectedRange.value = [start, end];
}

// Tabs 控制
const activeTab = ref("static");

// 静态时间预设按钮及对应时间范围函数
interface RangeItem {
  label: string;
  range: [string, string];
}

function getStartOfWeek(date: dayjs.Dayjs) {
  // 周一作为一周开始
  return date.startOf("week").add(1, "day");
}

function getLastWeekRange() {
  const lastWeekStart = getStartOfWeek(dayjs().subtract(1, "week"));
  const lastWeekEnd = lastWeekStart.add(6, "day");
  return [lastWeekStart.format("YYYY-MM-DD"), lastWeekEnd.format("YYYY-MM-DD")];
}

const staticRanges: RangeItem[] = [
  {
    label: "今日",
    range: [dayjs().format("YYYY-MM-DD"), dayjs().format("YYYY-MM-DD")],
  },
  {
    label: "昨日",
    range: [
      dayjs().subtract(1, "day").format("YYYY-MM-DD"),
      dayjs().subtract(1, "day").format("YYYY-MM-DD"),
    ],
  },
  {
    label: "本周",
    range: [
      getStartOfWeek(dayjs()).format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ],
  },
  {
    label: "上周",
    range: getLastWeekRange(),
  },
  {
    label: "本月",
    range: [
      dayjs().startOf("month").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ],
  },
  {
    label: "上月",
    range: [
      dayjs().subtract(1, "month").startOf("month").format("YYYY-MM-DD"),
      dayjs().subtract(1, "month").endOf("month").format("YYYY-MM-DD"),
    ],
  },
  {
    label: "本年",
    range: [
      dayjs().startOf("year").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ],
  },
  {
    label: "去年",
    range: [
      dayjs().subtract(1, "year").startOf("year").format("YYYY-MM-DD"),
      dayjs().subtract(1, "year").endOf("year").format("YYYY-MM-DD"),
    ],
  },
  {
    label: "过去7天",
    range: [
      dayjs().subtract(6, "day").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ],
  },
  {
    label: "过去30天",
    range: [
      dayjs().subtract(29, "day").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ],
  },
  {
    label: "过去90天",
    range: [
      dayjs().subtract(89, "day").format("YYYY-MM-DD"),
      dayjs().format("YYYY-MM-DD"),
    ],
  },
];

// 静态时间按钮点击，设置选中范围
function selectStaticRange(range: [string, string]) {
  console.log("静态时间范围", range);
  const dateStart = dayjs(range[0]).valueOf();
  const dateEnd = dayjs(range[1]).valueOf();
  // selectedRange.value = range;
  console.log("[dateStart, dateEnd]", [dateStart, dateEnd]);
  selectedRange.value = [dateStart, dateEnd];

  // 切换到静态tab时，动态时间模块的值清空
  // dynamicRange.value = null
  pastNDays.value.nDays = "1";
  dynamicType.value = "specific";
}

// 动态时间模块控制
const dynamicType = ref<"specific" | "pastNDays">("specific");

// 具体时间范围，绑定动态时间范围选择器
// const dynamicRange = ref<[string, string] | null>(null)

// 过去N天输入框
interface pastNDays {
  nDays: string;
}

const pastNDays = ref<pastNDays>({
  nDays: "1",
});

// 过去N天，校验大于1的正整数
const rules = {
  nDays: [
    {
      require: true,
      message: "请输入正整数",
    },

    {
      pattern: /^[1-9]\d*$/,
      message: "请输入正整数",
      trigger: ["blur", "change"],
    },
  ],
};

const formRef = ref(null);

// 过去N天确认按钮点击，计算对应时间范围并赋值
function confirmPastNDays() {
  formRef.value?.validate((valid: any) => {
    if (valid) {
      console.log("过去N天", pastNDays.value.nDays);
      const end = dayjs();
      const start = end.subtract(pastNDays.value.nDays - 1, "day");
      const range: [string, string] = [
        start.format("YYYY-MM-DD"),
        end.format("YYYY-MM-DD"),
      ];
      const dateStart = dayjs(range[0]).valueOf();
      const dateEnd = dayjs(range[1]).valueOf();
      selectedRange.value = [dateStart, dateEnd];
    } else {
      ElMessage.error("表单验证失败，请检查输入");
      return false;
    }
  });
}

// 监听 Tabs 切换时，清理对应状态
watch(activeTab, (val) => {
  if (val === "static") {
    // 清理动态时间
    // dynamicRange.value = null
    pastNDays.value.nDays = "1";
    dynamicType.value = "specific";
  } else if (val === "dynamic") {
    // 清理静态时间选中
    selectedRange.value = null;
  }
});

// 监听动态类型切换，清理对应数据
watch(dynamicType, (val) => {
  if (val === "specific") {
    pastNDays.value.nDays = "1";
  } else {
    // dynamicRange.value = null
  }
});

// 监听底部时间范围选择器变化，更新动态时间范围（如果在动态tab且类型是具体时间）
function onSelectedRangeChange(val: [string, string]) {
  const dateStart = dayjs(val[0]).valueOf();
  const dateEnd = dayjs(val[1]).valueOf();
  selectedRange.value = [dateStart, dateEnd];
}

const setDateRange1 = inject("setDateRange");
const onHandleConfirm = () => {
  console.log("最终选中时间范围", selectedRange.value);
  if (selectedRange.value) {
    const start = dayjs(selectedRange.value[0]).format("YYYY-MM-DD");
    const end = dayjs(selectedRange.value[1]).format("YYYY-MM-DD");
    getDateRange.value = [start, end];
    console.log("getDateRange", getDateRange.value);
    setDateRange1(getDateRange.value);
  } else {
    ElMessage.warning("请选择时间范围");
  }
};

const resetDateRange1 = inject("resetDateRange");
const resetDateRange = () => {
  resetDateRange1(null);
};

const cancelDateRange = () => {
  // setDateRange1(getDateRange.value);
};
</script>

<style scoped lang="scss">
.date-content {
  margin: 16px;
  padding: 16px;
  // min-width: 600px;
  max-width: 1000px !important;
  border: 1px solid #ccc;
}

.static-buttons {
  width: 400px;
  // 将元素定义为网格容器
  display: grid;
  // 定义网格的列结构和大小
  // 创建2个列，每个列宽度为1fr（1 fractional unit）
  grid-template-columns: repeat(2, 1fr);
  // 定义网格间隙
  gap: 12px 20px;
  margin-top: 12px;

  :deep(.el-button) {
    width: 100px;
    text-align: center;
    margin-left: 0;
  }
}

// 动态时间
.dynamic-btn {
  margin-bottom: 12px;
}

// 过去N天
.past-n-days {
  margin-left: 20px;
}
</style>
